package com.travel.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@Slf4j
@Configuration
public class CorsFilter implements Filter {
    /**
     * 请求域白名单
     */
    private final List<String> allowOrigins = Arrays.asList( "http://8.142.20.7", "http://localhost:8081", "http://localhost:8080", "http://192.168.0.104:8080");

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
        /* 允许Cookie */
        httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
        /* 允许白名单的域发起跨域请求 */
        String origin = ((HttpServletRequest) servletRequest).getHeader("Origin");
        log.warn("url : " + ((HttpServletRequest) servletRequest).getRequestURL().toString());
//        log.info("New request Origin : " + origin);
        httpResponse.setHeader("Access-Control-Allow-Origin", origin/* allowOrigins.contains(origin) ? origin : "" */);
//        httpResponse.setHeader("Vary", "Origin");
        /* 允许请求方式 */
        httpResponse.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
        /* 允许所有请求头 */
        httpResponse.setHeader("Access-Control-Allow-Headers", "Content-Type, token");
        if ("OPTIONS".equals(((HttpServletRequest) servletRequest).getMethod())) {
            servletResponse.getWriter().println("success");
            return;
        }

        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void init(FilterConfig filterConfig) {
    }

    @Override
    public void destroy() {
    }
}
